package com.lebang.medicalInquiry.service;

import com.alibaba.fastjson.JSONObject;
import com.lebang.medicalInquiry.component.RedisComponent;
import com.lebang.medicalInquiry.constant.RedisKeyEnum;
import com.lebang.medicalInquiry.mapper.ArticleClassifyMapper;

import com.lebang.medicalInquiry.mapper.ArticleMapper;
import com.lebang.medicalInquiry.model.po.Article;
import com.lebang.medicalInquiry.model.po.ArticleClassify;
import com.lebang.medicalInquiry.utils.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleService {

    @Resource
    private ArticleClassifyMapper articleClassfiyMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Autowired
    private RedisComponent redisComponent;


    public List<ArticleClassify> getArticleClassfiy() {
        List<ArticleClassify> allEnable = new ArrayList<>();
        Object value = redisComponent.getValue(RedisKeyEnum.article_classify_list.getName());
        if (TextUtil.isEmpty(value)) {
            allEnable = articleClassfiyMapper.getAllEnable();
            redisComponent.setValue(RedisKeyEnum.article_classify_list.getName(), JSONObject.toJSONString(allEnable));
        } else {
            allEnable = JSONObject.parseArray(value.toString(), ArticleClassify.class);
        }
        return allEnable;
    }

    public List<Article> getArticle(String keyWord, Integer classifyId, int page, Integer limit) {
        List<Article> articles = articleMapper.getArticleByCondition(classifyId, keyWord, page, limit);
        articles.forEach(article->{
            String content = article.getContent().replaceAll("[^\u4e00-\u9fa5]", "");
            if(!TextUtil.isEmpty(content)){
                article.setContent(content.substring(0, Math.min(content.length(), 30)));
            }

        });
        return articles;
    }

    public Article getArticleInfo(Integer articleId) {
        return articleMapper.selectByPrimaryKey(articleId);
    }
}
